<?php namespace Phpcmf\Library\Usu_fanyi; // 这里的Test是应用目录


class Lang {

    private $lang;
    private $file;
    private $config;
    private $URL;
    private $APP_ID;
    private $SEC_KEY;
    private $count;
    public $error;

    public function __construct() {
        $this->config = \Phpcmf\Service::M('app')->get_config('Usu_fanyi');
        $this->URL = "http://api.fanyi.baidu.com/api/trans/vip/translate";
        $this->APP_ID = $this->config['appid'];
        $this->SEC_KEY = $this->config['appsecret'];
        $this->count = 0;
    }

    public function zhiyi($text, $lang) {
      
        if(strlen($text)>2){
              if ($this->lang && isset($this->lang[$text])) {
            return $this->lang[$text];
        } 
                $this->file = WRITEPATH.'config/usu_fanyi_lang_'.$lang.'.php';
        
        if (is_file($this->file)) {
            $this->lang = require $this->file;
            if (isset($this->lang[$text])) {
                
                return $this->lang[$text];
            }
        } else {
            $this->lang = [];
        } 
       
   
  
        if ($this->count > 20 ){
            return $text;
        }
//     
        $rt = $this->translate($text, 'auto', $lang);
        if ($rt) {
                // 吸入文件
            $this->count++;
            $this->lang[$text] = $rt;
            file_put_contents($this->file, '<?php return '.var_export($this->lang, true).';');
        }
 }
        return $rt; }

    

    public function fanyi($text, $lang) {

        if (IS_ADMIN && !$this->config['use']) {
            // 表示没有开启了后台界面翻译
            return $text;
        }

       return $this->zhiyi($text,$lang);
    }


//翻译入口
    function translate($query, $from, $to)
    {
        $args = array(
            'q' => $query,
            'appid' => $this->APP_ID,
            'salt' => rand(10000,99999),
            'from' => $from,
            'to' => $to,

        );
        $args['sign'] = $this->buildSign($query, $this->APP_ID, $args['salt'], $this->SEC_KEY);
        $ret = $this->call($this->URL, $args);
        $ret = json_decode($ret, true);

        if ($ret['trans_result'][0]['dst']) {
            
            return $ret['trans_result'][0]['dst'];
        } elseif ($ret['error_code']) {
            $this->error = '错误代码（'.$ret['error_code'].'）'.$ret['error_msg'];
        }

        return '';
    }

//加密
    function buildSign($query, $appID, $salt, $secKey)
    {/*{{{*/
        $str = $appID . $query . $salt . $secKey;
        $ret = md5($str);
        return $ret;
    }/*}}}*/

//发起网络请求
    function call($url, $args=null, $method="post", $testflag = 0, $timeout = 10, $headers=array())
    {/*{{{*/
        $ret = false;
        $i = 0;
        while($ret === false)
        {
            if($i > 1)
                break;
            if($i > 0)
            {
                sleep(1);
            }
            $ret = $this->callOnce($url, $args, $method, false, $timeout, $headers);
            $i++;
        }
        return $ret;
    }/*}}}*/

    function callOnce($url, $args=null, $method="post", $withCookie = false, $timeout = 10, $headers=array())
    {/*{{{*/
        $ch = curl_init();
        if($method == "post")
        {
            $data = $this->convert($args);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            curl_setopt($ch, CURLOPT_POST, 1);
        }
        else
        {
            $data = $this->convert($args);
            if($data)
            {
                if(stripos($url, "?") > 0)
                {
                    $url .= "&$data";
                }
                else
                {
                    $url .= "?$data";
                }
            }
        }
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        if(!empty($headers))
        {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        }
        if($withCookie)
        {
            curl_setopt($ch, CURLOPT_COOKIEJAR, $_COOKIE);
        }
        $r = curl_exec($ch);
        curl_close($ch);
        return $r;
    }/*}}}*/

    function convert(&$args)
    {/*{{{*/
        $data = '';
        if (is_array($args))
        {
            foreach ($args as $key=>$val)
            {
                if (is_array($val))
                {
                    foreach ($val as $k=>$v)
                    {
                        $data .= $key.'['.$k.']='.rawurlencode($v).'&';
                    }
                }
                else
                {
                    $data .="$key=".rawurlencode($val)."&";
                }
            }
            return trim($data, "&");
        }
        return $args;
    }/*}}}*/

}